package com.xu.controller;


import com.xu.pojo.UserDto;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {



    @RequestMapping({"/"})
    public String index(){return "login";}

    @PostMapping("/login")
    public String login(int userid,String password, Model model, HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(String.valueOf(userid), password);
        try {
            subject.login(token);
            UserDto user = (UserDto)subject.getPrincipal();
            session.setAttribute("loginUser",user.getUserName());
            return "redirect:/user/home";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(Model model){
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipal()!=null) {
            subject.logout();
            //session.invalidate(); //logout 已自动调用了HttpSession.invalidate();
            model.addAttribute("msg", "用户已注销");
        }
        return "login";
    }


    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }


    @RequestMapping("/user/home")
    public String home(RedirectAttributesModelMap modelMap){
        Subject subject = SecurityUtils.getSubject();
        UserDto userDto = (UserDto)subject.getPrincipal();
        switch (userDto.getRoles()){
            case "admin": return "redirect:/admin/selectManage";
            case "teacher": return "redirect:/tea/queryMyCourse";
            case "student": return "redirect:/stu/queryCourse";
            default: return "redirect:/user/toInfo";
        }
    }




}
